
package com.feib.soeasy.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feib.soeasy.model.User;
import com.feib.soeasy.model.UserActionLog;
import com.feib.soeasy.service.UserActionLogService;
import com.feib.soeasy.util.SpringContextUtil;
import com.feib.soeasy.util.UserUtil;

import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.ExecutionContext;
import net.sourceforge.stripes.controller.Interceptor;
import net.sourceforge.stripes.controller.Intercepts;
import net.sourceforge.stripes.controller.LifecycleStage;


/**
 * @title (#)UserActionLogInterceptor.java<br>
 * @description 畫面操作紀錄Interceptor<br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/1 create by Jimmy Liu<br>
 */
@Intercepts( { LifecycleStage.HandlerResolution, LifecycleStage.RequestComplete })
public class UserActionLogInterceptor implements Interceptor {
    
    public final static String ACCESS_LOG_KEY = "__EBILLING_ACCESS_LOG_KEY";
    
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    

    /**
     * Invoked when intercepting the flow of execution.
     *
     * @param context the ExecutionContext of the request currently being processed
     * @return the result of calling context.proceed(), or if the interceptor wishes to change
     *         the flow of execution, a Resolution
     * @throws Exception if any non-recoverable errors occur
     */
    @Override
    public Resolution intercept(ExecutionContext context) throws Exception {
        UserActionLog actionLog = null;
        ActionBeanContext actionBeanContext = context.getActionBeanContext();
        HttpServletRequest request = actionBeanContext.getRequest();
        actionLog = (UserActionLog) request.getAttribute(ACCESS_LOG_KEY);
        
        //Request結束，將Log存至DB
        if (LifecycleStage.RequestComplete.equals(context.getLifecycleStage()) && null != actionLog)
        {
            actionLog.setOutDateTime(new Date());
            log(actionLog);
            request.removeAttribute(ACCESS_LOG_KEY);
        }
        
        //往下一個Lifecycle Stage
        Resolution resolution = context.proceed();
        
        ActionBean actionBean = context.getActionBean();
        
        
        //request中無 AccessLog物件，則建立並存放在Request中
        if (null == actionLog && LifecycleStage.HandlerResolution.equals(context.getLifecycleStage()))
        {
            actionLog = new UserActionLog();
            actionLog.setInDateTime(new Date());
            actionLog.setActionBean(actionBean.getClass().getSimpleName());
            actionLog.setEventName(context.getHandler().getName());
            //電腦ip or proxy
            actionLog.setRemoteAddr(request.getRemoteAddr());
            
            User user =  UserUtil.getUser();
            if (null != user)
            {
                actionLog.setUserPk(user.getUserPk());
                actionLog.setUserId(user.getUserId());
                actionLog.setUsernName(user.getUserName());
                actionLog.setGroupNo(user.getGroup().getGroupNo());
                actionLog.setGroupPk(user.getGroup().getGroupPk());
                actionLog.setGroupName(user.getGroup().getGroupName());
                
                actionLog.setActionName(UserUtil.getCurrentMenuItemName());
                
                if (null != UserUtil.getCurrentMenuItem())
                {
                	if (null != UserUtil.getCurrentMenuItem().getParentMenuItem())
                		actionLog.setParentActionName(UserUtil.getCurrentMenuItem().getParentMenuItem().getActionName());
                	else
                		logger.debug("UserUtil.getCurrentMenuItem().getParentMenuItem() is null");
                }
                else
                {
                	logger.debug("UserUtil.getCurrentMenuItem() is null");
                }
                
            }
            
            request.setAttribute(ACCESS_LOG_KEY, actionLog);
        }
        
        return resolution;
    }
    
    private void log(UserActionLog accessLog)
    {
        try {
            
            if (null != accessLog)
            {
                // WEB ATM 回CALL程式，不Log
                if ("Soez9999ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    return;
                
                if (null == accessLog.getActionName())
                {
                    if ("Soez1001ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("學雜費繳費");
                        accessLog.setParentActionName("帳單管理");
                    }
                    else if ("Soez1002ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("一般帳單繳費");
                        accessLog.setParentActionName("帳單管理");
                    }
                    else if ("Soez1002ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("學雜費繳費進度查詢");
                        accessLog.setParentActionName("帳單管理");
                    }
                    else if ("Soez1004ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("一般帳單繳費進度查詢");
                        accessLog.setParentActionName("帳單管理");
                    }
                    else if ("Soez1005ActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("繳費說明");
                        accessLog.setParentActionName("帳單管理");
                    }
                    else if ("LoginActionBean".equalsIgnoreCase(accessLog.getActionBean()))
                    {
                        accessLog.setActionName("系統登入");
                    }
                    
                }
                UserActionLogService accessLogService = (UserActionLogService)SpringContextUtil.getBean("userActionLogService");
                accessLogService.addUserActionLog(accessLog);
            }
        }
        catch (Exception e) {
            logger.warn("儲存畫面操作生錯誤:", e);
        }
    }

}
